package com.daijt.mobile.service.hibernate;

import java.util.List;

import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.stereotype.Service;

import com.daijt.mobile.persistence.User;
import com.daijt.mobile.service.UserService;

@Service
public class UserServiceImpl extends JpaDaoSupport implements UserService {

	public static final String GET_USER_BY_EMAIL = "from User u where email = ?1";
	
	@Autowired
	@Required
	public void setJpaEntityManagerFactory(
	        @Qualifier("entityManagerFactory")EntityManagerFactory entityManagerFactory) {
		super.setEntityManagerFactory(entityManagerFactory);
	}
	
	public User getUserById(long userId) {
		return getJpaTemplate().find(User.class, userId);
	}

	public User getUserByEmail(String email) {
		@SuppressWarnings("unchecked")
		List<User> users = (List<User>)getJpaTemplate().find(GET_USER_BY_EMAIL, new Object[]{email});
		
		if (users.size() == 0)
			return null;
		else
			return users.get(0);
	}

	public User updateUser(User user) {
		
		return getJpaTemplate().merge(user);
	}

}
